package com.ebraga.trackerclub.android.view.service;

import java.util.Calendar;
import java.util.concurrent.ScheduledFuture;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.ebraga.trackerclub.android.handler.api.SyncDataHandler;
import com.ebraga.trackerclub.android.handler.service.SyncDataServiceHandler;
import com.ebraga.trackerclub.android.util.DLog;
import com.ebraga.trackerclub.android.util.SynchManager;
import com.ebraga.trackerclub.android.util.api.AndroidContext;
import com.ebraga.trackerclub.android.util.core.AndroidContextImpl;

public class SyncDataService extends IntentService {
	
	private ScheduledFuture<?> scheduleWithFixedDelay;
	
	public SyncDataService() {
		super(SyncDataService.class.getName());
	}	
	
	@Override
	public void onHandleIntent(Intent intent) {
		
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MILLISECOND, (int) SynchManager.INTERVAL_SYNCH);
		SynchManager.setRepeatingAlarmForSynch(this, cal.getTimeInMillis());
		
		try {
			Log.d("SYNC: ", "SYNC");
			SyncDataHandler syncDataHandler = new SyncDataServiceHandler(getAndroidContext());
			syncDataHandler.doSync();
			
		} catch (Throwable e) {
			DLog.e(e);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(scheduleWithFixedDelay != null)
			scheduleWithFixedDelay.cancel(false);
		
	}
	
	private AndroidContext getAndroidContext() {
		AndroidContext context = new AndroidContextImpl();

		context.setContext(getApplicationContext());
		return context;
	}			

}